package com.ningjingjing.servlet;


import com.ningjingjing.model.User;
import com.ningjingjing.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 读取用户写下的信息
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        try {
            // 2. 通过 MySQL 查询，得到用户对象
            User user = query(username, password);
            if (user == null) {
                // 查不到对应的用户，代表用户名密码错误
                resp.sendRedirect("/login.html");
                return;
            }

            // 3. 完成登录
            HttpSession session = req.getSession();
            session.setAttribute("currentUser", user);

            // 4. 引导用户去首页
            resp.sendRedirect("/");
        } catch (SQLException exc) {
            throw new ServletException(exc);
        }
    }

    private User query(String username, String password) throws SQLException {
        password = hash(password);
        try (Connection c = DBUtil.getConnection()) {
            String sql = "SELECT uid, nickname FROM user WHERE username = ? AND password = ?";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setString(1, username);
                s.setString(2, password);

                try (ResultSet rs = s.executeQuery()) {
                    if (!rs.next()) {
                        return null;
                    }

                    User user = new User();
                    user.uid = rs.getInt("uid");
                    user.username = username;
                    user.nickname = rs.getString("nickname");

                    return user;
                }
            }
        }
    }

    private String hash(String password) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");

            byte[] bytes = password.getBytes("UTF-8");
            byte[] digest = messageDigest.digest(bytes);
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();

        }  catch (Exception exc) {
            return password;
        }
    }
}
